import http from '@ohos.net.http';
import { HUAWEI_AUTH_URL } from './const';
export const getToken = (account:string,IAMname:string,password:string)=>{
    let httpRequest = http.createHttp();
    return new Promise<string>((resolve,reject)=>{
        httpRequest.request(`${HUAWEI_AUTH_URL}/v3/auth/tokens`,
            {
                method:http.RequestMethod.POST,
                header:{
                    "Content-Type": "application/json;charset=utf8"
                },
                extraData: {
                    "auth": {
                        "identity": {
                            "methods": [
                                "password"
                            ],
                            "password": {
                                "user": {
                                    "domain": {
                                        "name": account
                                    },
                                    "name": IAMname,
                                    "password": password
                                }
                            }
                        },
                        "scope": {}
                    }
                },
                readTimeout: 2000,
                connectTimeout: 2000
            }).then((resp=>{
                if(resp.responseCode>=200 && resp.responseCode<300){
                    resolve(resp.header["X-Subject-Token"][0])
                }else{
                    reject(resp.result)
                }
        }))
    })
}
export class checkTokenResp{
    token:{
        expires_at:string
    }
}
export const checkToken = (token:string)=>{
    let httpRequest = http.createHttp()
    return new Promise<boolean>((resolve,reject)=>{
        httpRequest.request(`${HUAWEI_AUTH_URL}/v3/auth/tokens`,
            {
                header:{
                    "Content-Type": "application/json;charset=utf8",
                    "X-Auth-Token": token,
                    "X-Subject-Token": token
                },
                method:http.RequestMethod.GET
            }).then((resp)=>{
            if(resp.responseCode>=200 && resp.responseCode<300){
                //2023-04-08T14:23:12.748000Z
                const obj = JSON.parse(resp.result as string) as checkTokenResp
                // openharmony环境下的Date.parse不支持毫秒部分，所以需要去掉毫秒
                const date = Date.parse(obj.token.expires_at.split(".")[0])
                const now = Date.now()
                if(date<now){
                    resolve(true)
                }else{
                    resolve(false)
                }
            }else{
                resolve(false)
            }
        })
    })
}

